package com.qsi.app.golf.db;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.List;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.MappingSqlQuery;
import org.springframework.jdbc.object.SqlUpdate;

import com.qsi.app.golf.model.Golfer;

public class GolfSpringDAO implements GolfDAO {

	/** Logger for this class and subclasses */
    protected final Log logger = LogFactory.getLog(getClass());

    private DataSource ds;

    public List getGolfers() {
        logger.info("Getting Golfers!");
        GolferQuery query = new GolferQuery(ds);
        return query.execute();
    }

    public void createGolfer(Golfer golfer) {
        logger.debug("Attempting to save golfer " + golfer.getFirstName() + golfer.getLastName());
        SqlUpdate su =
            new SqlUpdate(ds, "INSERT INTO golfer (id, first_name, last_name) VALUES (NULL, ?, ?)");
        su.declareParameter(new SqlParameter("first_name", Types.VARCHAR));
        su.declareParameter(new SqlParameter("last_name", Types.VARCHAR));
        su.compile();
        Object[] oa = new Object[2];
        oa[0] = new String(golfer.getFirstName());
        oa[1] = new String(golfer.getLastName());
        su.update(oa);
    }

    public void setDataSource(DataSource ds) {
        this.ds = ds;
    }

    class GolferQuery extends MappingSqlQuery {
        GolferQuery(DataSource ds) {
            super(ds, "SELECT id ID, first_name FIRST_NAME, last_name LAST_NAME FROM golfer");
            compile();
        }

        protected Object mapRow(ResultSet rs, int rowNum) throws SQLException {
            Golfer golfer = new Golfer();
            golfer.setId(rs.getInt("ID"));
            golfer.setFirstName(rs.getString("FIRST_NAME"));
            golfer.setLastName(rs.getString("LAST_NAME"));
            return golfer;
        }
    }
}
